"""
智能项目生成器

根据项目分析结果自动生成项目文件结构和内容。
"""

import os
from pathlib import Path
from typing import Dict, List, Any, Optional
from dataclasses import dataclass

from .project_analyzer import ProjectInfo, ProjectType, Complexity
from .file_manager import FileManager


@dataclass
class GeneratedFile:
    """生成的文件信息"""
    path: str
    content: str
    description: str
    dependencies: List[str] = None


class ProjectTemplate:
    """项目模板类"""
    
    def __init__(self):
        self.templates = {
            ProjectType.SINGLE_PAGE: self._get_single_page_templates,
            ProjectType.GAME: self._get_game_templates,
            ProjectType.WEB_APP: self._get_web_app_templates,
            ProjectType.API_SERVICE: self._get_api_templates,
            ProjectType.DESKTOP_APP: self._get_desktop_app_templates,
            ProjectType.MOBILE_APP: self._get_mobile_app_templates,
            ProjectType.LIBRARY: self._get_library_templates,
            ProjectType.SCRIPT: self._get_script_templates
        }
    
    def get_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取项目模板文件"""
        template_func = self.templates.get(project_info.project_type, self._get_generic_templates)
        return template_func(project_info)
    
    def _get_single_page_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取单页面项目模板"""
        files = []
        
        # HTML模板
        html_content = self._generate_html_template(project_info)
        files.append(GeneratedFile(
            path="index.html",
            content=html_content,
            description="主HTML文件，包含页面结构"
        ))
        
        # CSS模板
        if "css" in project_info.languages:
            css_content = self._generate_css_template(project_info)
            files.append(GeneratedFile(
                path="style.css",
                content=css_content,
                description="CSS样式文件"
            ))
        
        # JavaScript模板
        if "javascript" in project_info.languages:
            js_content = self._generate_javascript_template(project_info)
            files.append(GeneratedFile(
                path="script.js",
                content=js_content,
                description="JavaScript功能文件"
            ))
        
        return files
    
    def _get_game_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取游戏项目模板"""
        files = []
        
        # HTML游戏模板
        html_content = self._generate_game_html_template(project_info)
        files.append(GeneratedFile(
            path="index.html",
            content=html_content,
            description="游戏HTML文件，包含canvas元素"
        ))
        
        # 游戏JavaScript模板
        js_content = self._generate_game_js_template(project_info)
        files.append(GeneratedFile(
            path="game.js",
            content=js_content,
            description="游戏逻辑JavaScript文件"
        ))
        
        # 游戏CSS模板
        css_content = self._generate_game_css_template(project_info)
        files.append(GeneratedFile(
            path="style.css",
            content=css_content,
            description="游戏样式CSS文件"
        ))
        
        return files
    
    def _get_web_app_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取Web应用模板"""
        files = []
        
        # 基础HTML
        html_content = self._generate_web_app_html_template(project_info)
        files.append(GeneratedFile(
            path="index.html",
            content=html_content,
            description="Web应用主HTML文件"
        ))
        
        # 主JavaScript文件
        js_content = self._generate_web_app_js_template(project_info)
        files.append(GeneratedFile(
            path="app.js",
            content=js_content,
            description="Web应用主JavaScript文件"
        ))
        
        # 样式文件
        css_content = self._generate_web_app_css_template(project_info)
        files.append(GeneratedFile(
            path="style.css",
            content=css_content,
            description="Web应用样式文件"
        ))
        
        # 如果使用React
        if "react" in project_info.frameworks:
            react_content = self._generate_react_component_template(project_info)
            files.append(GeneratedFile(
                path="src/App.js",
                content=react_content,
                description="React主组件文件"
            ))
        
        return files
    
    def _get_api_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取API服务模板"""
        files = []
        
        # 主Python文件
        python_content = self._generate_api_python_template(project_info)
        files.append(GeneratedFile(
            path="main.py",
            content=python_content,
            description="API服务主文件"
        ))
        
        # 依赖文件
        requirements_content = self._generate_requirements_template(project_info)
        files.append(GeneratedFile(
            path="requirements.txt",
            content=requirements_content,
            description="Python依赖文件"
        ))
        
        # README文件
        readme_content = self._generate_readme_template(project_info)
        files.append(GeneratedFile(
            path="README.md",
            content=readme_content,
            description="项目说明文档"
        ))
        
        return files
    
    def _get_desktop_app_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取桌面应用模板"""
        return self._get_generic_templates(project_info)
    
    def _get_mobile_app_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取移动应用模板"""
        return self._get_generic_templates(project_info)
    
    def _get_library_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取库项目模板"""
        return self._get_generic_templates(project_info)
    
    def _get_script_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取脚本模板"""
        return self._get_generic_templates(project_info)
    
    def _get_generic_templates(self, project_info: ProjectInfo) -> List[GeneratedFile]:
        """获取通用模板"""
        return [
            GeneratedFile(
                path="main.py",
                content="# 主程序文件\nprint('Hello, World!')",
                description="主程序文件"
            )
        ]
    
    # HTML模板生成方法
    def _generate_html_template(self, project_info: ProjectInfo) -> str:
        """生成HTML模板"""
        title = self._extract_title_from_description(project_info.description)
        
        return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>{title}</h1>
        </header>
        
        <main>
            <div class="content">
                <p>欢迎使用{title}！</p>
                <!-- 在这里添加您的内容 -->
            </div>
        </main>
        
        <footer>
            <p>&copy; 2024 {title}</p>
        </footer>
    </div>
    
    <script src="script.js"></script>
</body>
</html>"""
    
    def _generate_game_html_template(self, project_info: ProjectInfo) -> str:
        """生成游戏HTML模板"""
        title = self._extract_title_from_description(project_info.description)
        
        return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="game-container">
        <header class="game-header">
            <h1>{title}</h1>
            <div class="game-info">
                <div class="score">得分: <span id="score">0</span></div>
                <div class="level">等级: <span id="level">1</span></div>
            </div>
        </header>
        
        <main class="game-main">
            <canvas id="gameCanvas" width="800" height="600"></canvas>
            <div class="game-controls">
                <button id="startBtn">开始游戏</button>
                <button id="pauseBtn">暂停</button>
                <button id="resetBtn">重新开始</button>
            </div>
        </main>
        
        <div class="game-instructions">
            <h3>游戏说明</h3>
            <p>使用方向键控制游戏角色</p>
        </div>
    </div>
    
    <script src="game.js"></script>
</body>
</html>"""
    
    def _generate_web_app_html_template(self, project_info: ProjectInfo) -> str:
        """生成Web应用HTML模板"""
        title = self._extract_title_from_description(project_info.description)
        
        return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="app">
        <header class="app-header">
            <h1>{title}</h1>
            <nav class="app-nav">
                <!-- 导航菜单 -->
            </nav>
        </header>
        
        <main class="app-main">
            <div class="app-content">
                <!-- 应用内容 -->
            </div>
        </main>
        
        <footer class="app-footer">
            <p>&copy; 2024 {title}</p>
        </footer>
    </div>
    
    <script src="app.js"></script>
</body>
</html>"""
    
    # CSS模板生成方法
    def _generate_css_template(self, project_info: ProjectInfo) -> str:
        """生成CSS模板"""
        return """/* 基础样式重置 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Arial', sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f4f4f4;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    min-height: 100vh;
}

header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
    border-bottom: 2px solid #007bff;
}

header h1 {
    color: #007bff;
    font-size: 2.5em;
    margin-bottom: 10px;
}

main {
    padding: 20px 0;
}

.content {
    background-color: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

footer {
    text-align: center;
    padding: 20px 0;
    border-top: 1px solid #ddd;
    color: #666;
    margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .container {
        padding: 10px;
    }
    
    header h1 {
        font-size: 2em;
    }
}"""
    
    def _generate_game_css_template(self, project_info: ProjectInfo) -> str:
        """生成游戏CSS模板"""
        return """/* 游戏样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Arial', sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    color: white;
}

.game-container {
    text-align: center;
    background: rgba(255, 255, 255, 0.1);
    padding: 20px;
    border-radius: 15px;
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.game-header {
    margin-bottom: 20px;
}

.game-header h1 {
    font-size: 2.5em;
    margin-bottom: 15px;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.game-info {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
}

.game-info div {
    background: rgba(255, 255, 255, 0.2);
    padding: 10px 20px;
    border-radius: 25px;
    font-weight: bold;
}

#gameCanvas {
    border: 3px solid white;
    border-radius: 10px;
    background-color: #000;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
    margin-bottom: 20px;
}

.game-controls {
    margin-bottom: 20px;
}

.game-controls button {
    background: linear-gradient(45deg, #ff6b6b, #ee5a24);
    color: white;
    border: none;
    padding: 12px 24px;
    margin: 0 10px;
    border-radius: 25px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.game-controls button:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}

.game-controls button:active {
    transform: translateY(0);
}

.game-instructions {
    background: rgba(255, 255, 255, 0.1);
    padding: 15px;
    border-radius: 10px;
    margin-top: 20px;
}

.game-instructions h3 {
    margin-bottom: 10px;
    color: #ffd700;
}

.game-instructions p {
    font-size: 14px;
    opacity: 0.9;
}"""
    
    def _generate_web_app_css_template(self, project_info: ProjectInfo) -> str:
        """生成Web应用CSS模板"""
        return """/* Web应用样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f8f9fa;
}

#app {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.app-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1rem 2rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.app-header h1 {
    font-size: 1.8rem;
    margin-bottom: 0.5rem;
}

.app-nav {
    display: flex;
    gap: 2rem;
}

.app-nav a {
    color: white;
    text-decoration: none;
    padding: 0.5rem 1rem;
    border-radius: 5px;
    transition: background-color 0.3s;
}

.app-nav a:hover {
    background-color: rgba(255, 255, 255, 0.2);
}

.app-main {
    flex: 1;
    padding: 2rem;
}

.app-content {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.app-footer {
    background-color: #343a40;
    color: white;
    text-align: center;
    padding: 1rem;
    margin-top: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .app-header {
        padding: 1rem;
    }
    
    .app-header h1 {
        font-size: 1.5rem;
    }
    
    .app-nav {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .app-main {
        padding: 1rem;
    }
    
    .app-content {
        padding: 1rem;
    }
}"""
    
    # JavaScript模板生成方法
    def _generate_javascript_template(self, project_info: ProjectInfo) -> str:
        """生成JavaScript模板"""
        return """// 主JavaScript文件
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成');
    
    // 初始化应用
    initializeApp();
});

function initializeApp() {
    // 在这里添加初始化代码
    console.log('应用初始化');
    
    // 示例：添加点击事件
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        button.addEventListener('click', handleButtonClick);
    });
}

function handleButtonClick(event) {
    console.log('按钮被点击:', event.target.textContent);
    
    // 在这里添加按钮点击处理逻辑
    showMessage('按钮被点击了！');
}

function showMessage(message) {
    // 创建消息提示
    const messageDiv = document.createElement('div');
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #007bff;
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        z-index: 1000;
        animation: slideIn 0.3s ease;
    `;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后移除消息
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
`;
document.head.appendChild(style);"""
    
    def _generate_game_js_template(self, project_info: ProjectInfo) -> str:
        """生成游戏JavaScript模板"""
        return """// 游戏主逻辑
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.score = 0;
        this.level = 1;
        this.gameRunning = false;
        this.gamePaused = false;
        
        // 游戏对象
        this.player = null;
        this.enemies = [];
        this.particles = [];
        
        // 游戏设置
        this.gameSpeed = 1;
        this.lastTime = 0;
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.createPlayer();
        this.updateDisplay();
    }
    
    setupEventListeners() {
        // 按钮事件
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('resetBtn').addEventListener('click', () => this.resetGame());
        
        // 键盘事件
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));
    }
    
    createPlayer() {
        this.player = {
            x: this.canvas.width / 2,
            y: this.canvas.height - 50,
            width: 30,
            height: 30,
            speed: 5,
            color: '#00ff00'
        };
    }
    
    startGame() {
        this.gameRunning = true;
        this.gamePaused = false;
        this.gameLoop();
        console.log('游戏开始');
    }
    
    togglePause() {
        this.gamePaused = !this.gamePaused;
        if (!this.gamePaused && this.gameRunning) {
            this.gameLoop();
        }
    }
    
    resetGame() {
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.level = 1;
        this.enemies = [];
        this.particles = [];
        this.createPlayer();
        this.updateDisplay();
        this.clearCanvas();
        console.log('游戏重置');
    }
    
    gameLoop(currentTime = 0) {
        if (!this.gameRunning || this.gamePaused) return;
        
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        this.update(deltaTime);
        this.render();
        
        requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    update(deltaTime) {
        // 更新游戏对象
        this.updateEnemies();
        this.updateParticles();
        this.checkCollisions();
    }
    
    updateEnemies() {
        // 生成敌人
        if (Math.random() < 0.02) {
            this.createEnemy();
        }
        
        // 更新敌人位置
        this.enemies.forEach((enemy, index) => {
            enemy.y += enemy.speed;
            
            // 移除超出屏幕的敌人
            if (enemy.y > this.canvas.height) {
                this.enemies.splice(index, 1);
            }
        });
    }
    
    updateParticles() {
        this.particles.forEach((particle, index) => {
            particle.x += particle.vx;
            particle.y += particle.vy;
            particle.life--;
            
            if (particle.life <= 0) {
                this.particles.splice(index, 1);
            }
        });
    }
    
    createEnemy() {
        const enemy = {
            x: Math.random() * (this.canvas.width - 20),
            y: -20,
            width: 20,
            height: 20,
            speed: 2 + Math.random() * 2,
            color: '#ff0000'
        };
        this.enemies.push(enemy);
    }
    
    checkCollisions() {
        this.enemies.forEach((enemy, enemyIndex) => {
            if (this.isColliding(this.player, enemy)) {
                // 碰撞处理
                this.createExplosion(enemy.x, enemy.y);
                this.enemies.splice(enemyIndex, 1);
                this.score += 10;
                this.updateDisplay();
            }
        });
    }
    
    isColliding(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
               rect1.x + rect1.width > rect2.x &&
               rect1.y < rect2.y + rect2.height &&
               rect1.y + rect1.height > rect2.y;
    }
    
    createExplosion(x, y) {
        for (let i = 0; i < 10; i++) {
            this.particles.push({
                x: x,
                y: y,
                vx: (Math.random() - 0.5) * 4,
                vy: (Math.random() - 0.5) * 4,
                life: 30,
                color: '#ffff00'
            });
        }
    }
    
    handleKeyPress(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        switch(e.key) {
            case 'ArrowLeft':
                this.player.x = Math.max(0, this.player.x - this.player.speed);
                break;
            case 'ArrowRight':
                this.player.x = Math.min(this.canvas.width - this.player.width, this.player.x + this.player.speed);
                break;
            case 'ArrowUp':
                this.player.y = Math.max(0, this.player.y - this.player.speed);
                break;
            case 'ArrowDown':
                this.player.y = Math.min(this.canvas.height - this.player.height, this.player.y + this.player.speed);
                break;
        }
    }
    
    render() {
        this.clearCanvas();
        
        // 绘制玩家
        this.drawRect(this.player);
        
        // 绘制敌人
        this.enemies.forEach(enemy => this.drawRect(enemy));
        
        // 绘制粒子效果
        this.particles.forEach(particle => this.drawParticle(particle));
    }
    
    clearCanvas() {
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
    
    drawRect(obj) {
        this.ctx.fillStyle = obj.color;
        this.ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
    }
    
    drawParticle(particle) {
        this.ctx.fillStyle = particle.color;
        this.ctx.globalAlpha = particle.life / 30;
        this.ctx.fillRect(particle.x, particle.y, 2, 2);
        this.ctx.globalAlpha = 1;
    }
    
    updateDisplay() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('level').textContent = this.level;
    }
}

// 初始化游戏
const game = new Game();"""
    
    def _generate_web_app_js_template(self, project_info: ProjectInfo) -> str:
        """生成Web应用JavaScript模板"""
        return """// Web应用主JavaScript文件
class WebApp {
    constructor() {
        this.currentPage = 'home';
        this.data = {};
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.loadInitialData();
        this.render();
    }
    
    setupEventListeners() {
        // 导航事件
        document.addEventListener('click', (e) => {
            if (e.target.matches('[data-page]')) {
                e.preventDefault();
                this.navigateTo(e.target.dataset.page);
            }
        });
        
        // 表单提交事件
        document.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleFormSubmit(e.target);
        });
    }
    
    navigateTo(page) {
        this.currentPage = page;
        this.render();
        console.log(`导航到: ${page}`);
    }
    
    handleFormSubmit(form) {
        const formData = new FormData(form);
        const data = Object.fromEntries(formData);
        
        console.log('表单数据:', data);
        
        // 处理表单数据
        this.processFormData(data);
    }
    
    processFormData(data) {
        // 在这里处理表单数据
        this.showNotification('数据已提交！');
    }
    
    loadInitialData() {
        // 加载初始数据
        this.data = {
            user: { name: '用户', email: 'user@example.com' },
            settings: { theme: 'light', language: 'zh-CN' }
        };
    }
    
    render() {
        this.renderHeader();
        this.renderMain();
        this.renderFooter();
    }
    
    renderHeader() {
        const header = document.querySelector('.app-header');
        if (header) {
            header.innerHTML = `
                <h1>Web应用</h1>
                <nav class="app-nav">
                    <a href="#" data-page="home">首页</a>
                    <a href="#" data-page="about">关于</a>
                    <a href="#" data-page="contact">联系</a>
                </nav>
            `;
        }
    }
    
    renderMain() {
        const main = document.querySelector('.app-content');
        if (main) {
            switch(this.currentPage) {
                case 'home':
                    main.innerHTML = this.renderHomePage();
                    break;
                case 'about':
                    main.innerHTML = this.renderAboutPage();
                    break;
                case 'contact':
                    main.innerHTML = this.renderContactPage();
                    break;
                default:
                    main.innerHTML = this.renderHomePage();
            }
        }
    }
    
    renderHomePage() {
        return `
            <h2>欢迎使用Web应用</h2>
            <p>这是一个现代化的Web应用程序。</p>
            <div class="features">
                <div class="feature-card">
                    <h3>功能1</h3>
                    <p>描述功能1的内容</p>
                </div>
                <div class="feature-card">
                    <h3>功能2</h3>
                    <p>描述功能2的内容</p>
                </div>
            </div>
        `;
    }
    
    renderAboutPage() {
        return `
            <h2>关于我们</h2>
            <p>这是关于页面的内容。</p>
            <p>我们致力于提供优质的服务。</p>
        `;
    }
    
    renderContactPage() {
        return `
            <h2>联系我们</h2>
            <form class="contact-form">
                <div class="form-group">
                    <label for="name">姓名:</label>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="email">邮箱:</label>
                    <input type="email" id="email" name="email" required>
                </div>
                <div class="form-group">
                    <label for="message">消息:</label>
                    <textarea id="message" name="message" rows="5" required></textarea>
                </div>
                <button type="submit">发送消息</button>
            </form>
        `;
    }
    
    renderFooter() {
        const footer = document.querySelector('.app-footer');
        if (footer) {
            footer.innerHTML = `
                <p>&copy; 2024 Web应用. 保留所有权利.</p>
            `;
        }
    }
    
    showNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'notification';
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 1000;
            animation: slideIn 0.3s ease;
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new WebApp();
});"""
    
    # Python模板生成方法
    def _generate_api_python_template(self, project_info: ProjectInfo) -> str:
        """生成API Python模板"""
        return """#!/usr/bin/env python3
# -*- coding: utf-8 -*-
\"\"\"
API服务主文件
\"\"\"

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import uvicorn

# 创建FastAPI应用实例
app = FastAPI(
    title="API服务",
    description="一个基于FastAPI的Web API服务",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 数据模型
class Item(BaseModel):
    id: Optional[int] = None
    name: str
    description: Optional[str] = None
    price: float

class ItemResponse(BaseModel):
    success: bool
    message: str
    data: Optional[Item] = None

# 模拟数据库
items_db = []
next_id = 1

@app.get("/")
async def root():
    \"\"\"根路径\"\"\"
    return {"message": "欢迎使用API服务！", "version": "1.0.0"}

@app.get("/health")
async def health_check():
    \"\"\"健康检查\"\"\"
    return {"status": "healthy", "service": "API服务"}

@app.get("/items", response_model=List[Item])
async def get_items():
    \"\"\"获取所有项目\"\"\"
    return items_db

@app.get("/items/{item_id}", response_model=ItemResponse)
async def get_item(item_id: int):
    \"\"\"根据ID获取项目\"\"\"
    for item in items_db:
        if item["id"] == item_id:
            return ItemResponse(
                success=True,
                message="项目获取成功",
                data=Item(**item)
            )
    
    raise HTTPException(status_code=404, detail="项目未找到")

@app.post("/items", response_model=ItemResponse)
async def create_item(item: Item):
    \"\"\"创建新项目\"\"\"
    global next_id
    
    new_item = {
        "id": next_id,
        "name": item.name,
        "description": item.description,
        "price": item.price
    }
    
    items_db.append(new_item)
    next_id += 1
    
    return ItemResponse(
        success=True,
        message="项目创建成功",
        data=Item(**new_item)
    )

@app.put("/items/{item_id}", response_model=ItemResponse)
async def update_item(item_id: int, item: Item):
    \"\"\"更新项目\"\"\"
    for i, existing_item in enumerate(items_db):
        if existing_item["id"] == item_id:
            updated_item = {
                "id": item_id,
                "name": item.name,
                "description": item.description,
                "price": item.price
            }
            items_db[i] = updated_item
            
            return ItemResponse(
                success=True,
                message="项目更新成功",
                data=Item(**updated_item)
            )
    
    raise HTTPException(status_code=404, detail="项目未找到")

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    \"\"\"删除项目\"\"\"
    for i, item in enumerate(items_db):
        if item["id"] == item_id:
            deleted_item = items_db.pop(i)
            return {
                "success": True,
                "message": "项目删除成功",
                "data": deleted_item
            }
    
    raise HTTPException(status_code=404, detail="项目未找到")

if __name__ == "__main__":
    print("启动API服务...")
    print("访问 http://localhost:8000/docs 查看API文档")
    uvicorn.run(app, host="0.0.0.0", port=8000)"""
    
    def _generate_requirements_template(self, project_info: ProjectInfo) -> str:
        """生成requirements.txt模板"""
        requirements = ["fastapi>=0.104.0", "uvicorn[standard]>=0.24.0"]
        
        if "数据库" in project_info.features:
            requirements.extend([
                "sqlalchemy>=2.0.0",
                "alembic>=1.12.0"
            ])
        
        if "用户认证" in project_info.features:
            requirements.extend([
                "python-jose[cryptography]>=3.3.0",
                "passlib[bcrypt]>=1.7.4",
                "python-multipart>=0.0.6"
            ])
        
        return "\n".join(requirements)
    
    def _generate_readme_template(self, project_info: ProjectInfo) -> str:
        """生成README模板"""
        title = self._extract_title_from_description(project_info.description)
        
        return f"""# {title}

## 项目描述

{project_info.description}

## 技术栈

- **编程语言**: {', '.join(project_info.languages)}
- **框架**: {', '.join(project_info.frameworks) if project_info.frameworks else '无'}
- **功能特性**: {', '.join(project_info.features) if project_info.features else '无'}

## 安装和运行

### 环境要求

- Python 3.8+
- pip

### 安装依赖

```bash
pip install -r requirements.txt
```

### 运行项目

```bash
python main.py
```

## API文档

启动服务后，访问以下地址查看API文档：

- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc

## 项目结构

```
.
├── main.py              # 主程序文件
├── requirements.txt     # 依赖文件
├── README.md           # 项目说明
└── ...
```

## 贡献

欢迎提交Issue和Pull Request！

## 许可证

MIT License"""
    
    def _generate_react_component_template(self, project_info: ProjectInfo) -> str:
        """生成React组件模板"""
        return """import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('欢迎使用React应用！');

  useEffect(() => {
    // 组件挂载时的逻辑
    console.log('组件已挂载');
  }, []);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  const handleDecrement = () => {
    setCount(count - 1);
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>React应用</h1>
        <p>{message}</p>
        
        <div className="counter">
          <h2>计数器: {count}</h2>
          <div className="buttons">
            <button onClick={handleDecrement}>-</button>
            <button onClick={handleIncrement}>+</button>
          </div>
        </div>
        
        <div className="features">
          <h3>功能特性</h3>
          <ul>
            <li>React Hooks</li>
            <li>状态管理</li>
            <li>事件处理</li>
            <li>生命周期</li>
          </ul>
        </div>
      </header>
    </div>
  );
}

export default App;"""
    
    def _extract_title_from_description(self, description: str) -> str:
        """从描述中提取标题"""
        # 简单的标题提取逻辑
        if "贪吃蛇" in description or "snake" in description.lower():
            return "贪吃蛇游戏"
        elif "游戏" in description or "game" in description.lower():
            return "游戏应用"
        elif "网站" in description or "web" in description.lower():
            return "Web应用"
        elif "API" in description or "接口" in description:
            return "API服务"
        else:
            return "我的项目"


class ProjectGenerator:
    """项目生成器主类"""
    
    def __init__(self):
        self.template = ProjectTemplate()
        self.file_manager = FileManager()
    
    def generate_project(self, project_info: ProjectInfo, output_dir: str = ".") -> List[str]:
        """
        生成项目文件
        
        Args:
            project_info: 项目信息
            output_dir: 输出目录
            
        Returns:
            List[str]: 生成的文件路径列表
        """
        generated_files = []
        
        # 获取模板文件
        template_files = self.template.get_templates(project_info)
        
        # 创建输出目录
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        # 生成文件
        for template_file in template_files:
            file_path = output_path / template_file.path
            
            # 确保目录存在
            file_path.parent.mkdir(parents=True, exist_ok=True)
            
            # 写入文件内容
            try:
                self.file_manager.write_file(str(file_path), template_file.content, overwrite=True)
                generated_files.append(str(file_path))
                print(f"✅ 生成文件: {file_path}")
            except Exception as e:
                print(f"❌ 生成文件失败 {file_path}: {e}")
        
        # 创建项目结构目录
        self._create_project_directories(project_info, output_path)
        
        return generated_files
    
    def _create_project_directories(self, project_info: ProjectInfo, output_path: Path):
        """创建项目目录结构"""
        structure = project_info.suggested_structure
        
        for directory in structure.get("directories", []):
            dir_path = output_path / directory
            dir_path.mkdir(parents=True, exist_ok=True)
            print(f"📁 创建目录: {dir_path}")
    
    def generate_project_summary(self, project_info: ProjectInfo, generated_files: List[str]) -> str:
        """生成项目摘要"""
        summary = f"""
🎉 项目生成完成！

📋 项目信息:
• 项目类型: {project_info.project_type.value}
• 复杂度: {project_info.complexity.value}
• 编程语言: {', '.join(project_info.languages)}
• 框架: {', '.join(project_info.frameworks) if project_info.frameworks else '无'}
• 功能特性: {', '.join(project_info.features) if project_info.features else '无'}
• 预计文件数: {project_info.estimated_files}

📁 生成的文件:
"""
        
        for file_path in generated_files:
            summary += f"• {file_path}\n"
        
        summary += f"""
🚀 下一步操作:
1. 查看生成的文件
2. 根据需要修改代码
3. 运行项目进行测试
4. 添加更多功能

💡 提示: 所有文件都已生成，可以直接运行！
        """
        
        return summary.strip()
